package com.cinema.servlet.admin;

import com.cinema.dao.MovieDAO;
import com.cinema.dao.ShowtimeDAO;
import com.cinema.dao.UserDAO;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.cinema.util.DBUtil;

/**
 * 管理员统计报表Servlet
 */
public class AdminStatisticsServlet extends HttpServlet {
    private MovieDAO movieDAO = new MovieDAO();
    private ShowtimeDAO showtimeDAO = new ShowtimeDAO();
    private UserDAO userDAO = new UserDAO();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        try {
            // 获取统计数据
            Map<String, Object> statistics = getStatistics();
            
            request.setAttribute("statistics", statistics);
            request.getRequestDispatcher("/admin/statistics.jsp").forward(request, response);
            
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取统计数据失败");
            request.getRequestDispatcher("/error/500.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
    
    /**
     * 获取统计数据
     */
    private Map<String, Object> getStatistics() {
        Map<String, Object> stats = new HashMap<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            
            // 1. 电影总数
            String movieCountSql = "SELECT COUNT(*) as count FROM movies";
            pstmt = conn.prepareStatement(movieCountSql);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                stats.put("totalMovies", rs.getInt("count"));
            }
            rs.close();
            pstmt.close();
            
            // 2. 今日场次数
            String todayShowtimesSql = "SELECT COUNT(*) as count FROM showtimes WHERE show_date = CURDATE()";
            pstmt = conn.prepareStatement(todayShowtimesSql);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                stats.put("todayShowtimes", rs.getInt("count"));
            }
            rs.close();
            pstmt.close();
            
            // 3. 总用户数
            String userCountSql = "SELECT COUNT(*) as count FROM users";
            pstmt = conn.prepareStatement(userCountSql);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                stats.put("totalUsers", rs.getInt("count"));
            }
            rs.close();
            pstmt.close();
            
            // 4. 今日订单数（如果有订单表的话）
            try {
                String todayOrdersSql = "SELECT COUNT(*) as count FROM orders WHERE DATE(created_at) = CURDATE()";
                pstmt = conn.prepareStatement(todayOrdersSql);
                rs = pstmt.executeQuery();
                if (rs.next()) {
                    stats.put("todayOrders", rs.getInt("count"));
                }
            } catch (SQLException e) {
                // 如果订单表不存在，设置为0
                stats.put("todayOrders", 0);
            }
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            
            // 5. 正在上映的电影数
            String nowShowingSql = "SELECT COUNT(*) as count FROM movies WHERE status = 'NOW_SHOWING'";
            pstmt = conn.prepareStatement(nowShowingSql);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                stats.put("nowShowingMovies", rs.getInt("count"));
            }
            rs.close();
            pstmt.close();
            
            // 6. 即将上映的电影数
            String comingSoonSql = "SELECT COUNT(*) as count FROM movies WHERE status = 'COMING_SOON'";
            pstmt = conn.prepareStatement(comingSoonSql);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                stats.put("comingSoonMovies", rs.getInt("count"));
            }
            rs.close();
            pstmt.close();
            
            // 7. 总场次数
            String totalShowtimesSql = "SELECT COUNT(*) as count FROM showtimes";
            pstmt = conn.prepareStatement(totalShowtimesSql);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                stats.put("totalShowtimes", rs.getInt("count"));
            }
            rs.close();
            pstmt.close();
            
            // 8. 本周新增用户数
            try {
                String weeklyUsersSql = "SELECT COUNT(*) as count FROM users WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
                pstmt = conn.prepareStatement(weeklyUsersSql);
                rs = pstmt.executeQuery();
                if (rs.next()) {
                    stats.put("weeklyNewUsers", rs.getInt("count"));
                }
            } catch (SQLException e) {
                stats.put("weeklyNewUsers", 0);
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
            // 设置默认值
            stats.put("totalMovies", 0);
            stats.put("todayShowtimes", 0);
            stats.put("totalUsers", 0);
            stats.put("todayOrders", 0);
            stats.put("nowShowingMovies", 0);
            stats.put("comingSoonMovies", 0);
            stats.put("totalShowtimes", 0);
            stats.put("weeklyNewUsers", 0);
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
        
        return stats;
    }
}
